package com.string.actortv;

import android.app.Application;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.util.Log;

import java.lang.reflect.Method;

public class APPApplication extends Application {

    /**
     * 获取当前app version code
     */
    public static long getAppVersionCode() {
        long appVersionCode = 0;
        try {
            PackageInfo packageInfo = getInstance().getApplicationContext()
                    .getPackageManager()
                    .getPackageInfo(getInstance().getPackageName(), 0);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                appVersionCode = packageInfo.getLongVersionCode();
            } else {
                appVersionCode = packageInfo.versionCode;
            }
        } catch (PackageManager.NameNotFoundException e) {
            Log.e("fw_create", "e:" + e.toString());
        }
        return appVersionCode;
    }

    /**
     * 获取当前app version name
     */
    public static String getAppVersionName() {
        String appVersionName = "";
        try {
            PackageInfo packageInfo = getInstance().getApplicationContext()
                    .getPackageManager()
                    .getPackageInfo(getInstance().getPackageName(), 0);
            appVersionName = packageInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            Log.e("fw_create", "e:" + e.toString());
        }
        return appVersionName;
    }

    public static Application getInstance() {
        Application application = null;
        try {
            Class atClass = Class.forName("android.app.ActivityThread");
            Method currentApplicationMethod = atClass.getDeclaredMethod("currentApplication");
            currentApplicationMethod.setAccessible(true);
            application = (Application) currentApplicationMethod.invoke(null);
        } catch (Exception e) {
            Log.e("fw_create", "e:" + e.toString());
        }

        if (application != null) {
            return application;
        }

        try {
            Class atClass = Class.forName("android.app.AppGlobals");
            Method currentApplicationMethod = atClass.getDeclaredMethod("getInitialApplication");
            currentApplicationMethod.setAccessible(true);
            application = (Application) currentApplicationMethod.invoke(null);
        } catch (Exception e) {
            Log.e("fw_create", "e:" + e.toString());
        }

        return application;
    }

    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();
    }

}
